/**
 * Created by De Niro on 15-1-30.
 */
var app = angular.module('myApp', []);
app.directive('regPhone', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
            var regPhone = /^1[34578]{1}\d{9}$/;
            scope.$watch(attrs.ngModel, function() {
                if (regPhone.exec($(element).val()))
                    ctrl.$setValidity('regphone', true);
                else {
                    ctrl.$setValidity('regphone', false);
                }
            });
        }
    }
});

app.directive('regPsw', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
            var regPsw = /.{6,}/;
            scope.$watch(attrs.ngModel, function() {
                if (regPsw.exec($(element).val()))
                    ctrl.$setValidity('regpsw', true);
                else {
                    ctrl.$setValidity('regpsw', false);
                }
            });
        }
    }
});

app.directive('pswRepeat', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
            scope.$watch(attrs.ngModel, function() {
                if (scope.passwordRepeat == scope.password && !isEmpty(scope.password)) {
                    console.log(true);
                    scope.regForm.pswRepeat.$setValidity('repeat', true);
                } else {
                    scope.regForm.pswRepeat.$setValidity('repeat', false);
                }
            });
        }
    }
});

app.directive('verifyCode', function($http) {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
            var url = urls.urlCheckVerifyCode;
            scope.$watch(attrs.ngModel, function() {
                var data = {
                    verfiCode: $(element).val()
                };
                $http.post(url, data, postCfg(data))
                    .success(function(data) {
                        if (data.status == 1) {
                            ctrl.$setValidity('correct', true);
                        } else {
                            ctrl.$setValidity('correct', false);
                        }
                    })
                    .error(function(data) {
                        ctrl.$setValidity('correct', false);
                    });

            });
        }
    }
});
app.directive('raterFilter', function($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function() {
                    //根据controller的关系是选择$emit或者$broadcast
                    setTimeout(function() {
                        $('.rank').each(function() {
                            $(this).rater({
                                active: true,
                                style: 'inline-normal',
                                maxvalue: 5
                            });
                        });
                    }, 200);
                });
            }
        }
    };
});

function jiaOrYiChooseController($scope) {
    if ($.inArray(window.location.pathname, jiaFangUrl) > -1) {
        $scope.isYiFang = false;
    } else if ($.inArray(window.location.pathname, notJiaOrYi) > -1) {
        $scope.isYiFang = null;
    } else {
        $scope.isYiFang = true;
    }
}

function loginController($scope, $http) {
    $scope.password = '';
    $scope.username = '';
    $scope.submit = function() {
        $scope.loginForm.$setValidity('validate', true);
        var url = urls.urlLogin,
            data = {
                phone: $scope.username,
                passwd: hex_md5($scope.password)
            },
            transFn = function(data) {
                return $.param(data);
            },
            postCfg = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                transformRequest: transFn
            };
        if ($scope.username == '') {
            alert("请输入账号");
            return;
        }
        if ($scope.password == '') {
            alert("请输入密码");
            return;
        }

        $http.post(url, data, postCfg)
            .success(function(data) {
                //$scope.response = data;
                if (data.status) {
                    window.location.href = urls.urlFetch;
                } else {
                    $scope.loginForm.$setValidity('validate', false);
                }
            });
    };
}

function registerController($scope, $http) {
    $scope.sex = 0;
    $scope.isAgree = false;
    $scope.timer = 60;
    $scope.timeInterval;
    $scope.timerIsShow = false;
    var codeTimer = function() {
        var updateTimer = function() {
            $scope.timer--;
            if ($scope.timer <= 0) {
                $scope.timerIsShow = false;
                clearInterval($scope.timeInterval);
            }
        };
        $scope.timeInterval = setInterval(function() {
            $scope.$apply(updateTimer);
        }, 1000);

        $scope.timerIsShow = true;
        updateTimer();
    };
    $scope.getVerifyCode = function() {
        var url = urls.urlGetVerifyCode + '/phone/' + $scope.phone;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                // alert("验证码已发送");
                codeTimer();
            } else {
                $scope.codeMsg = data.info;
            }
        });
    };
    $scope.submit = function() {
        if ($scope.regForm.$invalid) {
            return;
        }
        var url = urls.urlRegister,
            data = {
                user_name: $scope.username,
                passwd: hex_md5($scope.password),
                sex: $scope.sex,
                verficode: $scope.verifyCode,
                phone: $scope.phone
            },
            transFn = function(data) {
                return $.param(data);
            },
            postCfg = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                transformRequest: transFn
            };

        $http.post(url, data, postCfg)
            .success(function(data) {
                if (data.status == 1) {
                    window.location.href = urls.urlResumeModify;
                } else {
                    alert(data.info);
                }
            });
    };
}

function ProfileBaseController($scope, $http) {
    $scope.userBase = '';
    $scope.trustInfo = '';
    $scope.firstInfo = '';
    $scope.firstInfoShow = true;
    $scope.secondInfo = '';
    $scope.hasFavored = 1;
    $scope.missions = '';
    $scope.hasTrusted = 1;
    $scope.missionId = '';
    $scope.trustShow = 1;
    $scope.headShow = 1;
    $scope.sexPicPath = 'male';
    $scope.hash = window.location.hash.split('#')[1];
    $scope.user_id = window.location.search.split('=')[1].split('&')[0];
    $scope.mission_id = window.location.search.split('=')[2];
    var defaultString = '------';

    // var left = $('#position-title').offset().left;
    // $('.work-title').css('marginLeft', left);

    $scope.tablist = function(hashname) {
        $scope.hash = hashname;
        window.location.hash = hashname;
    };
    $scope.getBaseInfo = function() {
        var url = urls.urlProfileBase + '/user_id/' + $scope.user_id;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.userBase = data.url;
                if ($scope.userBase.sex == 2) {
                    $scope.userBase.sexMeaning = '女';
                    $scope.sexPicPath = "female";
                } else {
                    $scope.userBase.sexMeaning = '男';
                    $scope.sexPicPath = "male";
                }
                if ($scope.userBase.collect_status == 2) {
                    $scope.hasFavored = 2;
                } else {
                    $scope.hasFavored = 1;
                }
                if ($scope.userBase.image_url == '') {
                    $scope.headShow = 2;
                }
                if ($scope.userBase.address.indexOf('null') != -1 || !$scope.userBase.address) {
                    $scope.userBase.address = defaultString;
                }
                $scope.userBase.degreeMeaning = genDegreeInfo($scope.userBase) || defaultString;
                $scope.getPhone($scope.userBase.user_id);
            } else {
                $scope.userBase = '';
            }
        });
    };
    $scope.getTrustInfo = function() {
        var url = urls.urlGetTrustInfo + '/user_id/' + $scope.user_id;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.trustInfo = data.url;
                $scope.hasTrusted = $scope.trustInfo.is_trusted;
                $scope.trustShow = 2;
            } else {
                $scope.trustInfo = '';
                $scope.hasTrusted = 1;
                $scope.trustShow = 1;
            }
        });
        $http.get(urls.urlGetProj).success(function(data) {
            if (data.status == 1) {
                $scope.missions = data.url;
            } else {
                $scope.missions = '';
            }
        });
    };

    $scope.getProject = function() {
        $('#selectModal').modal('show');
        // $http.get(urls.urlGetProj).success(function(data) {
        //     if (data.status == 1) {
        //         $scope.missions = data.url;
        //     } else {
        //         $scope.missions = '';
        //     }
        // });
    };

    // $scope.getFirstInfo = function() {
    //     var url = urls.urlGetFirstInfo + '/user_id/' + $scope.user_id;
    //     $http.get(url).success(function(data) {
    //         if (data.status == 1) {
    //             $scope.firstInfo = data.url;
    //             if (!$scope.firstInfo.mission) {
    //                 return;
    //             };
    //             for (var i = 0; i < $scope.firstInfo.mission.length; i++) {
    //                 $scope.firstInfo.mission[i].durationMeaning = transDuration($scope.firstInfo.mission[i].duration);
    //                 $scope.firstInfo.mission[i].salary = transSalary($scope.firstInfo.mission[i].salary1, $scope.firstInfo.mission[i].salary2);
    //                 $scope.firstInfo.mission[i].location = transLocation($scope.firstInfo.mission[i].location1, $scope.firstInfo.mission[i].location2);
    //             }
    //             // alert($scope.firstInfo.agent_j);
    //         } else {
    //             console.log(123);
    //             $scope.firstInfo = '';
    //         }
    //     });
    // };

    $scope.getFirstInfo = function(callback) {
        var url = urls.urlGetFirstInfo + '/user_id/' + $scope.user_id;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.firstInfo = data.url;
                // if (!$scope.firstInfo.agent_j) {
                //     $scope.firstInfo = false;
                // }
                if (!isEmpty($scope.firstInfo.mission)) {
                    var missions = $scope.firstInfo.mission;
                    for (var i = 0; i < missions.length; i++) {
                        missions[i].durationMeaning = transDuration(missions[i].duration);
                        missions[i].salary = transSalary(missions[i].salary1, missions[i].salary2);
                        missions[i].location = transLocation(missions[i].location1, missions[i].location2);
                    }
                } else {
                    $scope.firstInfo = '';
                    $scope.firstInfoShow = false;
                }
            } else {
                $scope.firstInfoShow = false;
            }
        });
    };

    $scope.getSecondInfo = function() {
        var url = urls.urlGetSecondInfo + '/user_id/' + $scope.user_id;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.secondInfo = data.url;
            } else {
                $scope.secondInfo = '';
            }
        });
    };

    $scope.select = function() {
        var url = urls.urlProfileSelect,
            data = {
                mission_id: $scope.missionId,
                follower_id: $('#userId').val()
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
                $('#selectModal').modal('hide');
                $scope.missions = '';
            });
    };

    $scope.favUser = function() {
        favUser($('#userId').val(), $http, $scope.getBaseInfo);
        // $scope.getBaseInfo();
    };

    $scope.delFavUser = function() {
        delFavUser($('#userId').val(), $http, $scope.getBaseInfo);
        // $scope.getBaseInfo();
    };

    $scope.trust = function() {
        var url = urls.urlProfileTrust + '/user_id/' + $('#userId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.hasTrusted = 2;
                $scope.getTrustInfo();
            } else {

            }
        });
    };

    $scope.delTrust = function() {
        var url = urls.urlProfileDelTrust + '/user_id/' + $('#userId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.hasTrusted = 1;
                $scope.getTrustInfo();
            } else {

            }
        });
    };

    $scope.getTrustNum = function() {
        if (!isEmpty($scope.trustInfo.truster_arr)) {
            return $scope.trustInfo.truster_arr.length;
        } else {
            return 0;
        }
    };

    $scope.getReportModal = function() {
        $('#reportModal').modal('show');
    };

    $scope.report = function() {
        var url = urls.urlProfileReport,
            data = {
                user_id: $('#userId').val(),
                content: $('#reportContent').val()
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    // alert('success');
                } else {
                    //                    alert(data.info);
                }
                $('#reportModal').modal('hide');
                $scope.reportCont = '';
            });
    };

    $scope.getPhone = function(id) {
        var url = urls.urlTaskContact + '/publisher_id/' + id;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                // $('#contactModal').modal('show');
                $scope.phone = data.url.phone;
            } else {
                $scope.phone = '';
            }
        });
    };

    $scope.publicToOne = function() {
        var url = urls.urlProfilePublicToOne,
            data = {
                user_id: $('#userId').val()
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    alert("您的资料已对该用户公开");
                } else {
                    //                    alert(data.info);
                }
            });
    };

    $scope.getFirstInfo();
    $scope.getBaseInfo();
    $scope.getTrustInfo();
    $scope.getSecondInfo();

    $scope.showClearPic = function(picPath) {
        // console.log(111);
        $("#clearPic").attr("src", picPath);
        $("#picModal").modal('show');
    }
}

function fetchIndexController($scope, $http) {
    $scope.hotSearch = ["导演", "华谊兄弟"];
    $scope.keyword = '';
    $scope.userName = '';
    $scope.jobs = '';
    $scope.scroll = false;
    $scope.missons = '';
    $scope.newKeyword = '';
    $scope.infoShow = false;
    $("#keyword-input").bind('keyup', function(event) {
        if (event.keyCode == 13) {
            $scope.search();
        }
    });

    getJobs($scope, $http);
    $scope.durations = application.getDurations();

    $scope.getAdvert = function() {
        var url = urls.urlNewslist;
        $http.get(url).success(function(data) {
            $scope.advert = data;
        });
    }

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
        $scope.search();
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
        $scope.search();
    };
    var page = 1;
    var row = 10;
    var url = urls.urlFetchSearch + '?page=' + page + '&row=' + row + '&jobs=&duration=';
    $http.get(url).success(function(data) {
        if (data.status == 1) {
            $scope.missions = data.url;
            for (var i = 0; i < $scope.missions.length; i++) {
                $scope.missions[i].durationMeaning = transDuration($scope.missions[i].duration);
                $scope.missions[i].salary = transSalary($scope.missions[i].salary1, $scope.missions[i].salary2);
                $scope.missions[i].location = transLocation($scope.missions[i].location1, $scope.missions[i].location2);
            }
        }
        page++;
    });
    // Search information of the second part with conditions.
    $scope.search = function() {
        var jobs = getActiveTag($scope.jobs, 'stat_name'),
            durations = getActiveTag($scope.durations, 'id');

        var url = urls.urlFetchSearch + '?keyword=' + $scope.keyword + '&page=1' + '&row=' + row + '&jobs=' + jobs + '&duration=' + durations;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.missions = data.url;
                for (var i = 0; i < $scope.missions.length; i++) {
                    $scope.missions[i].durationMeaning = transDuration($scope.missions[i].duration);
                    $scope.missions[i].salary = transSalary($scope.missions[i].salary1, $scope.missions[i].salary2);
                    $scope.missions[i].location = transLocation($scope.missions[i].location1, $scope.missions[i].location2);
                }
                $scope.newKeyword = $scope.keyword;
                page = 2;
            } else {
                $scope.missions = '';
                alert("没有满足搜索条件记录");
            }
        });
    };

    $scope.fetch = function() {
        var jobs = getActiveTag($scope.jobs, 'stat_name'),
            durations = getActiveTag($scope.durations, 'id');
        url = urls.urlFetchSearch + '?page=' + page + '&row=' + row + '&jobs=' + jobs + '&duration=' + durations + '&keyword=' + $scope.newKeyword;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                for (var i = 0; i < data.url.length; i++) {
                    data.url[i].durationMeaning = transDuration(data.url[i].duration);
                    data.url[i].salary = transSalary(data.url[i].salary1, data.url[i].salary2);
                    data.url[i].location = transLocation(data.url[i].location1, data.url[i].location2);
                }
                $scope.missions = $scope.missions.concat(data.url);
                page++;
            } else {
                // alert("没有更多信息");
                $scope.infoShow = true;
            }
        });
    };

    $scope.quickSearch = function(oneSearch) {
        $scope.keyword = oneSearch;
        $scope.search();
    };

    $scope.homepage = function(id) {
        window.location.href = urls.urlTaskIndex + "?mission=" + id;
    };

    $scope.getTimePast = getTimePastFunc;
    $scope.getAdvert();

    // $scope.search();
}

function fetchController($scope, $http) {
    $scope.hotSearch = ["导演", "华谊兄弟"];
    $scope.keyword = '';
    $scope.userName = '';
    $scope.jobs = '';
    $scope.scroll = false;
    $scope.missons = '';
    $scope.newKeyword = '';
    $scope.infoShow = false;
    $scope.advert = '';
    $("#keyword-input").bind('keyup', function(event) {
        if (event.keyCode == 13) {
            $scope.search();
        }
    });

    getJobs($scope, $http);
    $scope.durations = application.getDurations();

    $scope.getAdvert = function() {
        var url = urls.urlNewslist;
        $http.get(url).success(function(data) {
            $scope.advert = data;
        });
    }

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
        $scope.search();
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
        $scope.search();
    };
    var page = 1;
    var row = 10;
    var url = urls.urlFetchMission + '?page=' + page + '&row=' + row + '&jobs=&duration=';
    $http.get(url).success(function(data) {
        if (data.status == 1) {
            $scope.missions = data.url;
            for (var i = 0; i < $scope.missions.length; i++) {
                $scope.missions[i].durationMeaning = transDuration($scope.missions[i].duration);
                $scope.missions[i].salary = transSalary($scope.missions[i].salary1, $scope.missions[i].salary2);
                $scope.missions[i].location = transLocation($scope.missions[i].location1, $scope.missions[i].location2);
            }
        }
        page++;
    });
    // Search information of the second part with conditions.
    $scope.search = function() {
        var jobs = getActiveTag($scope.jobs, 'stat_name'),
            durations = getActiveTag($scope.durations, 'id');

        var url = urls.urlFetchMission + '?jobs=' + jobs + '&duration=' + durations;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.missions = data.url;
                for (var i = 0; i < $scope.missions.length; i++) {
                    $scope.missions[i].durationMeaning = transDuration($scope.missions[i].duration);
                    $scope.missions[i].salary = transSalary($scope.missions[i].salary1, $scope.missions[i].salary2);
                    $scope.missions[i].location = transLocation($scope.missions[i].location1, $scope.missions[i].location2);
                }
                $scope.newKeyword = $scope.keyword;
                page = 2;
            } else {
                $scope.missions = '';
                alert("没有满足搜索条件记录");
            }
        });
    };

    $scope.fetch = function() {
        var jobs = getActiveTag($scope.jobs, 'stat_name'),
            durations = getActiveTag($scope.durations, 'id');
        var url = urls.urlFetchMission + '?jobs=' + jobs + '&duration=' + durations;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                for (var i = 0; i < data.url.length; i++) {
                    data.url[i].durationMeaning = transDuration(data.url[i].duration);
                    data.url[i].salary = transSalary(data.url[i].salary1, data.url[i].salary2);
                    data.url[i].location = transLocation(data.url[i].location1, data.url[i].location2);
                }
                $scope.missions = $scope.missions.concat(data.url);
                page++;
            } else {
                // alert("没有更多信息");
                $scope.infoShow = true;
            }
        });
    };

    $scope.quickSearch = function(oneSearch) {
        $scope.keyword = oneSearch;
        $scope.search();
    };

    $scope.homepage = function(id) {
        window.location.href = urls.urlTaskIndex + "?mission=" + id;
    };

    $scope.getTimePast = getTimePastFunc;
    $scope.getAdvert();

    // $scope.search();
}

function resumeController($scope, $http, $timeout) {
    $scope.oldOrder = "";
    $scope.expId = "";
    $scope.firstExperience = "";
    $scope.otherExperience = "";
    $scope.sexPicPath = "male";
    $scope.resumeBase = '';
    $scope.isPublic = "1";
    $scope.intro = '';
    $scope.projectName = '';
    $scope.role = '';
    $scope.description = '';
    $scope.url = '';
    $scope.expAttach = {};
    var defaultString = '------';
    $scope.dragInit = function() {
        $timeout(function() {
            $('.movable-row.true').draggable({
                axis: 'y',
                containment: $('#work-experience-container'),
                handle: $('.movable-icon'),
                start: function(event, ui) {
                    $scope.oldOrder = parseInt($(this).attr('order'));
                    $scope.expId = $(this).attr('ng-id');
                }
            });
            $('.movable-row.droppable').droppable({
                tolerance: 'touch',
                drop: function(event, ui) {
                    var topOffset = parseInt(ui.draggable.css('top'), 10);
                    if (topOffset != 0 && !isNaN(topOffset)) {
                        console.log(ui.draggable.css('top'));
                        $(ui.draggable).removeAttr('style');
                        //$(event.target).removeAttr('style');
                        if (topOffset > 30 || topOffset < -30) {
                            //if(topOffset > 30){
                            //    //$(event.target).after(ui.draggable);
                            //    //$(ui.draggable).before(event.target);
                            //} else {
                            //    //$(event.target).after(ui.draggable);
                            //    //$(event.target).before(ui.draggable);
                            //}
                            $scope.newOrder = parseInt($(event.target).attr('order'));
                            if (!isNaN($scope.oldOrder) && !isNaN($scope.newOrder)) {
                                $scope.setExpOrder();
                                console.log("排序成功");
                            }
                        }

                        $(ui.draggable).attr('style', 'position: relative');
                        //$(event.target).attr('style', 'position: relative');
                        //$(ui.draggable).addClass('ui-droppable');
                    }

                }
            });
            $('#edit-movable-row').droppable({
                tolerance: 'touch',
                drop: function(event, ui) {
                    $(ui.draggable).removeAttr('style');
                    $(ui.draggable).attr('style', 'position: relative');
                }
            });
        }, 500);
    };
    $scope.setExpOrder = function() {
        var url = urls.urlResumeOrderExp + '?exp_id=' + $scope.expId + '&old_order=' + $scope.oldOrder + '&new_order=' + $scope.newOrder;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                if ((data.url != null) && (data.url != '')) {
                    $scope.otherExperience = data.url;
                    console.log(data.url);
                    $scope.firstExperience = $scope.otherExperience.shift();
                    $scope.dragInit();
                }
            } else {

            }
        });
    };

    $scope.getBaseInfo = function() {
        var url = urls.urlResumeBase;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.resumeBase = data.url;
                $scope.isPublic = $scope.resumeBase.is_public;
                $scope.intro = $scope.resumeBase.introduction;
                if ($scope.resumeBase.sex == 2) {
                    $scope.resumeBase.sexMeaning = '女';
                    $scope.sexPicPath = "female";
                } else {
                    $scope.resumeBase.sexMeaning = '男';
                    $scope.sexPicPath = "male";
                }
                $scope.resumeBase.degreeMeaning = genDegreeInfo($scope.resumeBase) || defaultString;
                // $scope.resumeBase.jobs = $scope.resumeBase.jobs || defaultString;
                $scope.resumeBase.duration = transDuration($scope.resumeBase.duration);
                if ($scope.resumeBase.address.indexOf('null') != -1 || !$scope.resumeBase.address) {
                    $scope.resumeBase.address = defaultString;
                }
                $scope.getAttach($scope.resumeBase.resume_id);
                if (($scope.resumeBase.experience != null) && ($scope.resumeBase.experience != '')) {
                    $scope.otherExperience = $scope.resumeBase.experience;
                    $scope.firstExperience = $scope.otherExperience.shift();
                    $scope.dragInit();
                }
            } else {
                $scope.resumeBase = '';
            }
        });
    };
    $scope.getBaseInfo();

    $scope.submit = function() {
        var url = urls.urlResumeEdit,
            data = {
                resume_id: $scope.resumeBase.resume_id,
                is_public: $scope.isPublic,
                introduction: $scope.intro,
                imageurls: '', //图片url需要拼接和拆分
                videourl: ''
            },
            transFn = function(data) {
                return $.param(data);
            },
            postCfg = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                transformRequest: transFn
            };

        $http.post(url, data, postCfg)
            .success(function(data) {
                if (data.status == 1) {
                    alert(data.info);
                    window.location.href = urls.urlResume;
                } else {
                    alert(data.info);
                }
            });
    }
    $scope.addExp = function() {
        var url = urls.urlResumeAddExp,
            data = {
                resume_id: $scope.resumeBase.resume_id,
                project_name: $scope.projectName,
                role: $scope.role,
                address: $scope.description,
                url: $scope.url,
                addonurl: ''
            },
            transFn = function(data) {
                return $.param(data);
            },
            postCfg = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                transformRequest: transFn
            };
        $http.post(url, data, postCfg).success(function(data) {

            if (data.status == 1) {
                alert(data.info);
                url = urls.urlResumeBase;
                $http.get(url).success(function(data) {
                    if (data.status == 1) {
                        if ((data.url.experience != null) && (data.url.experience != '')) {
                            $scope.otherExperience = data.url.experience;
                            $scope.firstExperience = $scope.otherExperience.shift();
                            $scope.dragInit();
                        }
                        $scope.projectName = '';
                        $scope.role = '';
                        $scope.description = '';
                        $scope.url = '';
                    }
                });
            } else {
                alert(data.info);
            }
        });

    }
    $scope.modify = function(experience) {
        experience.newProjectName = experience.project_name;
        experience.newRole = experience.role;
        experience.newDescription = experience.description;
        experience.newUrl = experience.url;
        experience.active = true;
        $scope.getExpAttach(experience.exp_id);
    }
    $scope.save = function(experience) {
        experience.active = false;
        var url = urls.urlResumeEditExp,
            data = {
                exp_id: experience.exp_id,
                resume_id: $scope.resumeBase.resume_id,
                project_name: experience.newProjectName,
                role: experience.newRole,
                address: experience.newDescription,
                url: experience.newUrl,
                addonurl: ''
            },
            transFn = function(data) {
                return $.param(data);
            },
            postCfg = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                transformRequest: transFn
            };
        $http.post(url, data, postCfg).success(function(data) {
            if (data.status == 1) {
                alert("修改成功");
                experience.project_name = experience.newProjectName;
                experience.role = experience.newRole;
                experience.description = experience.newDescription;
                experience.url = experience.newUrl;
                experience.active = false;
            } else {
                alert(data.info);
            }
        });
    }
    $scope.cancel = function(experience) {
        experience.active = false;
    }

    $scope.getExpAttach = function(id) {
        var url = urls.urlResumeGetExp + '/exp_id/' + id;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.expAttach[id] = data.url;
            } else {
                $scope.expAttach[id] = '';
            }
        });
    };

    $scope.delExpAttach = function(id, imageIndex) {
        var url = urls.urlResumeDelPhotoExp,
            data = {
                exp_id: id,
                image_url: $scope.expAttach[id][imageIndex].image_url
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    $scope.getExpAttach(id);
                } else {

                }
            });
    };


    //简历加项逻辑
    $scope.attach = '';
    $scope.images = new Array();
    $scope.spareId = 'image_url1';

    $scope.getAttach = function(id) {
        var url = urls.urlResumeAttach + '/resume_id/' + id;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.attach = data.url;
                $scope.images = new Array();
                if (!isEmpty($scope.attach.image)) {
                    for (var i = 0; i < $scope.attach.image.length; i++) {
                        for (img in $scope.attach.image[i]) {
                            $scope.images.push({
                                name: img,
                                url: $scope.attach.image[i][img]
                            });
                        }
                    }
                    genSpareId();
                }
            } else {
                $scope.attach = '';
                $scope.images = new Array();
            }
        });
    };

    $scope.delAttach = function(imageIndex) {
        var url = urls.urlResumeDelPhoto,
            data = {
                resume_id: $('#resumeId').val(),
                image_name: $scope.images[imageIndex].name,
                image_url: $scope.images[imageIndex].url
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    $scope.getAttach($('#resumeId').val());
                } else {
                    //                    alert(data.info);
                }
            });
    };

    /*$scope.delVideo = function() {
        var url = urls.urlResumeDelVideo,
            data = {
                resume_id: $scope.resumeId,
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    $scope.getAttach();
                } else {

                }
            });
    };*/

    // Inform server which slot to put image
    var genSpareId = function() {
        for (var i = 0; i < 8; i++) {
            if (i >= $scope.images.length) {
                $scope.spareId = 'image_url' + (i + Number(1));
                break;
            }

            var str = $scope.images[i].name;
            if (i != Number(str.charAt(str.length - 1)) - 1) {
                $scope.spareId = 'image_url' + (i + Number(1));
                break;
            }
        }
    };

}

function resumeProfileController($scope, $http) {
    $scope.user = '';
    $scope.jobs = '';
    $scope.birthday = new Date();
    $scope.degreeYears = application.getDegreeYears();

    $scope.province = '';
    $scope.city = '';
    $scope.provinces = application.getProvinces();
    $scope.cities = new Array();
    $scope.user_image = 1;

    $scope.isPublicBirthday = true;
    $scope.isPublicDegree = true;
    getJobs($scope, $http);
    $scope.durations = application.getDurations();

    // Province and city cascade
    $('#selectP').on('change', function() {
        var province = $(this).find("option:selected").text();
        $scope.cities = application.getCities()[province];
        $scope.city = '';
    });

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
    };

    $scope.getUserInfo = function() {
        $http.get(urls.urlResumeGetProfile).success(function(data) {
            if (data.status == 1) {
                $scope.user = data.url;
                if (($scope.user.birthday != null) && ($scope.user.birthday != '')) {
                    $scope.birthday = ($scope.user.birthday).split(' ')[0];
                }
                if (($scope.user.address != null) && ($scope.user.address != '')) {
                    $scope.province = $scope.user.address.split(',')[0];
                    $scope.cities = application.getCities()[$scope.province];
                    $scope.city = $scope.user.address.split(',')[1];
                }
                // $scope.isPublicBirthday = ($scope.user.ispublic_birthday == 1);
                // $scope.isPublicDegree = ($scope.user.ispublic_degree == 2);
                if ($scope.user.jobs != null) {
                    setActiveTag($scope.user.jobs, $scope.jobs, 'stat_name');
                } else {}
                if ($scope.user.duration != null) {
                    setActiveTag($scope.user.duration, $scope.durations, 'id');
                } else {}
                if ($scope.user.image_url != null) {
                    $scope.user_image = 2;
                }
            } else {
                $scope.user = '';
            }
        });
    };

    $scope.submit = function() {
        if ($scope.province != '') {
            $scope.user.address = $scope.province + "," + $scope.city;
        }

        var jobs, durations;
        if ($scope.jobs != null) {
            jobs = getActiveTag($scope.jobs, 'stat_name');
        }
        if ($scope.durations != null) {
            durations = getActiveTag($scope.durations, 'id');
        }

        url = urls.urlResumeSubmit,
            data = {
                image_url: $scope.user.image_url || 'default_avatar.png',
                user_name: $scope.user.user_name,
                birthday: $scope.birthday,
                jobs: jobs,
                duration: durations,
                sex: $scope.user.sex,
                address: $scope.user.address,
                degree_year: $scope.user.degree_year,
                degree_school: $scope.user.degree_school,
                degree_major: $scope.user.degree_major,
                ispublic_birthday: 2,
                ispublic_degree: ($scope.isPublicDegree * 1 + 1),
                agent_j: $scope.user.agent_j,
                agent_j_desc: $scope.user.agent_j_desc,
                agent_y: $scope.user.agent_y,
                agent_y_desc: $scope.user.agent_y_desc
            },
            transFn = function(data) {
                return $.param(data);
            },
            postCfg = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                transformRequest: transFn
            };

        $http.post(url, data, postCfg)
            .success(function(data) {
                if (data.status == 1) {
                    alert("修改成功！");
                    window.location.href = urls.urlResume;
                } else {
                    alert(data.info);
                }
            });
    };

    $scope.imgChange = function(src) {
        $scope.user.image_url = src;
        $scope.user_image = 2;
        $scope.$apply();
        $('#uploadModal').hide();
    };

    $scope.getUserInfo();
}

function publishSubmitController($scope, $http) {
    $scope.jobs = '';
    $scope.salary2 = '';
    $scope.location2 = '';
    $scope.salary = application.getSalary();
    $scope.locations = application.getLocations();
    $scope.province = '';
    $scope.city = '';
    $scope.provinces = application.getProvinces();
    $scope.cities = new Array();
    $scope.isPhonePublic = 1;
    $http.get(urls.urlGetJobs).success(function(data) {
        if (data.status == 1) {
            $scope.jobs = data.url;
            for (var i = 0; i < $scope.jobs.length; i++) {
                $scope.jobs[i].active = false;
            }
            $scope.jobMeaning = getActiveTag($scope.jobs, 'stat_name');
        } else {
            $scope.jobs = '';
        }
    });
    $scope.validTimes = application.getValidTime();
    $scope.durations = application.getDurations();
    $scope.durationMeaning = getActiveTag($scope.durations, 'id');


    // Province and city cascade
    $('#selectP').on('change', function() {
        var province = $(this).find("option:selected").text();
        $scope.city = '';
        $scope.cities = application.getCities()[province];
    });

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
        $scope.jobMeaning = getActiveTag($scope.jobs, 'stat_name');
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
        $scope.durationMeaning = getActiveTag($scope.durations, 'id');

    };

    $scope.submit = function() {
        if ($scope.location1 == 3) {
            $scope.location2 = $scope.province + ',' + $scope.city;
        } else {
            $scope.location2 = '';
        }

        if ($scope.salary1 != 1) {
            $scope.salary2 = '';
        }


        var jobs = getActiveTag($scope.jobs, 'stat_name'),
            durations = getActiveTag($scope.durations, 'id'),
            url = urls.urlPublishMission,
            data = {
                mission_name: $scope.missionName,
                jobs: jobs,
                duration: durations,
                salary1: $scope.salary1,
                salary2: $scope.salary2,
                location1: $scope.location1,
                location2: $scope.location2,
                description: $scope.description,
                valid_time: $scope.validTime,
                isphone_public: ($scope.isPhonePublic * 1) + 1,
                isagent: ($scope.isPhonePublic * 1) + 1
            },
            transFn = function(data) {
                return $.param(data);
            },
            postCfg = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                transformRequest: transFn
            };

        $http.post(url, data, postCfg)
            .success(function(data) {
                if (data.status == 1) {
                    alert("发布成功！");
                    console.log(data);
                    window.location.href = urls.urlTaskDetail + "?mission=" + data.url;
                } else {
                    alert(data.info);
                }
            });
    };
}

function setActiveTag(arr, tags, field) {
    for (var i = 0; i < tags.length; i++) {
        if (arr.indexOf(tags[i][field]) != -1) {
            tags[i].active = true;
        }
    }
}

function genDegreeInfo(info) {
    var resultArr = new Array();
    if (!isEmpty(info.degree_year))
        resultArr.push(info.degree_year);
    if (!isEmpty(info.degree_school))
        resultArr.push(info.degree_school);
    if (!isEmpty(info.degree_major))
        resultArr.push(info.degree_major);
    return resultArr.join(',');
}

function genDegreeInfoArray(infos) {
    var resultArr = [];
    infos.forEach(function(info) {
        var midResult = '';
        if (!isEmpty(info.degree_year))
            midResult = info.degree_year;
        if (!isEmpty(info.degree_school))
            midResult = midResult + ',' + info.degree_school;
        if (!isEmpty(info.degree_major))
            midResult = midResult + '.' + info.degree_major;
        resultArr.push(midResult);
    });
    return resultArr;
}

function getJobs($scope, $http) {
    $http.get(urls.urlGetJobs).success(function(data) {
        if (data.status == 1) {
            $scope.jobs = data.url;
            for (var i = 0; i < $scope.jobs.length; i++) {
                $scope.jobs[i].active = false;
            }
            // Initialize job list active state
            //            $scope.jobs[0].active = $scope.durations[0].active = true;
            // Hide more jobs
        } else {
            $scope.jobs = '';
        }
    });
}

function getActiveTag(arr, field) {
    var result = '';
    var tempArr = new Array();
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].active) {
            tempArr.push(arr[i][field]);
        }
    }
    result = tempArr.join(',');
    return result;
}

function transDuration(duration) {
    var durations = new Array();
    var result = new Array();
    if (!isEmpty(duration)) {
        durations = duration.split(',');
        for (var i = 0; i < durations.length; i++) {
            result.push(application.getDurations()[durations[i] - 1].name);
        }
    }
    return result.join(',');
}

function transValidTime(duration) {
    var durations = new Array();
    var result = new Array();
    if (!isEmpty(duration)) {
        durations = duration.split(',');
        for (var i = 0; i < durations.length; i++) {
            result.push(application.getValidTime()[durations[i] - 1].name);
        }
    }
    return result.join('，');
}

function transSalary(salary1, salary2) {
    var result = '';
    if (salary1 == 1) {
        result = salary2;
    } else if (salary1 == 2 || salary1 == 3) {
        result = application.getSalary()[salary1 - 1].name;
    }
    return result;
}

function transLocation(location1, location2) {
    var result = '';
    if (location1 == 3) {
        result = location2;
    } else if (location1 == 1 || location1 == 2) {
        result = application.getLocations()[location1 - 1].name;
    }
    return result;
}

function transExperience(experience) {
    if (experience) {
        return experience.project_name + ' ' + experience.role;
    } else {
        return '--';
    }

}

function isEmpty(obj) {
    return (obj == '' || obj == null || obj == undefined);
}

//message
function msgController($scope, $http) {
    $scope.msgSys = '';
    $scope.msgUser = '';
    $scope.hash = location.hash.split('#')[1];

    $scope.getMsgSys = function() {
        $http.get(urls.urlMessageGetSys).success(function(data) {
            if (data.status == 1) {
                $scope.msgSys = data.url;
            } else {
                $scope.msgSys = '';
            }
        });
    };

    $scope.getMsgUser = function() {
        $http.get(urls.urlMessageGetUser).success(function(data) {
            if (data.status == 1) {
                $scope.msgUser = data.url;
            } else {
                $scope.msgUser = '';
            }
        });
    };

    $scope.delFavUser = function(id) {
        delFavUser(id, $http, $scope.getBaseInfo);
        // $scope.getBaseInfo();
    };

    $scope.tablist = function(hashname) {
        $scope.hash = hashname;
    };


    $scope.getMsgSys();
    $scope.getMsgUser();
    $scope.getTimePast = getTimePastFunc;

}

function isEmpty(obj) {
    return (obj == '' || obj == null || obj == undefined);
}

//message
function msgSendController($scope, $http) {
    $scope.msgSys = '';
    $scope.msgUser = '';
    $scope.respond = '';
    $scope.error = false;
    $scope.leftWordsNumber = 500;
    $scope.tips = '还可以输入' + $scope.leftWordsNumber + '字';
    var refreshNumber = function() {
        var a = $scope.respond;
        $scope.leftWordsNumber = 500 - a.length;
        if ($scope.leftWordsNumber < 0) {
            $scope.leftWordsNumber = 0;
            $scope.error = true;
            $scope.tips = '字数超过500字!';
        } else {
            $scope.error = false;
            $scope.tips = '还可以输入' + $scope.leftWordsNumber + '字';
        }
    }
    $scope.$watch('respond', refreshNumber);
    var userName = $("#user-name").val(),
        publisherName = $("#publisher-name").val(),
        publisherId = $('#publisher-id').val();
    $scope.transferName = function(id) {
        if (id == publisherId) {
            return publisherName;
        } else {
            return userName;
        }
    }
    $scope.getMsgSys = function() {
        $http.get(urls.urlMessageGetSys).success(function(data) {
            if (data.status == 1) {
                $scope.msgSys = data.url;
            } else {
                $scope.msgSys = '';
            }
        });
    };

    $scope.getMsg = function() {
        var url = urls.urlMessageRecv + '/publisher_id/' + $('#publisher-id').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.msg = data.url;
            } else {
                $scope.msg = '';
            }
        });
    };


    $scope.getMsgSys();
    $scope.getMsg();
    $scope.submitMsg = function() {
        var url = urls.urlMessageSend,
            data = {
                publisher_id: publisherId,
                content: $scope.respond
            },
            transFn = function(data) {
                return $.param(data);
            },
            postCfg = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                transformRequest: transFn
            };

        $http.post(url, data, postCfg)
            .success(function(data) {
                if (data.status == 1) {
                    $scope.respond = '';
                    $scope.getMsg();
                } else {
                    //                    alert(data.info);
                }
            });
    };
    $scope.getTimePast = getTimePastFunc;
}

function msgCollectionController($scope, $http) {
    $scope.hash = location.hash.split('#')[1];
    $scope.goMission = function(id) {
        // alert(123);
        window.location.href = urls.urlTaskIndex + '?mission=' + id;
    }
    $scope.tablist = function(hashname) {
        $scope.hash = hashname;
    };

    $scope.userFav = '';
    $scope.missionFav = '';

    $scope.getFavUser = function() {
        $http.get(urls.urlFavGetUser).success(function(data) {
            if (data.status == 1) {
                $scope.userFav = data.url;
            } else {
                $scope.userFav = '';
            }
        });
    };
    $scope.getTimePast = getTimePastFunc;

    $scope.getFavMission = function() {
        $http.get(urls.urlFavGetMission).success(function(data) {
            if (data.status == 1) {
                $scope.missionFav = data.url;
                for (var i = 0; i < $scope.missionFav.length; i++) {
                    $scope.missionFav[i].durationMeaning = transDuration($scope.missionFav[i].duration);
                    $scope.missionFav[i].salaryMeaning = transSalary($scope.missionFav[i].salary1,
                        $scope.missionFav[i].salary2);
                    $scope.missionFav[i].locationMeaning = transLocation($scope.missionFav[i].location1,
                        $scope.missionFav[i].location2);
                }
            } else {
                $scope.missionFav = '';
            }
        });
    };
    var userId;
    $scope.delUserModal = function(user_id) {
        userId = user_id;
        $("#delUserModal").modal('show');
    }

    $scope.delFavUser = function() {
        var url = urls.urlFavDelUser + '/user_id/' + userId;
        console.log(url);
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                //                alert("删除成功");
                $("#delUserModal").modal('hide');
                $scope.getFavUser();
            } else {

            }
        });
    };


    var missionId;
    $scope.delMissionModal = function(mission_id) {
        missionId = mission_id;
        $("#delMissionModal").modal('show');
    }

    $scope.delFavMission = function() {
        var url = urls.urlFavDelMission + '/mission_id/' + missionId;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                //                alert("删除成功");
                $("#delMissionModal").modal('hide');
                $scope.getFavMission();
            } else {

            }
        });
    };


    $scope.getFavUser();
    $scope.getFavMission();
}

function missionController($scope, $http) {
    $scope.mission = '';
    $scope.publisher = '';
    $scope.publisher_name = '';
    $scope.publisher_id = '';
    $scope.trustInfo = '';
    $scope.trustNum = '';
    $scope.hasFavored = 1;
    $scope.hasTrusted = 1;
    $scope.phone = "";
    $scope.trustShow = 1;

    $scope.getTrustInfo = function(user_id) {
        var url = urls.urlGetTrustInfo + '/user_id/' + user_id;
        $http.get(url).success(function(data) {
            // alert(data);
            if (data.status == 1) {
                $scope.trustInfo = data.url.truster_arr;
                $scope.hasTrusted = data.url.is_trusted;
                $scope.trustNum = data.url.truster_arr.length;
                $scope.trustShow = 2;
            } else {
                $scope.trustInfo = '';
            }
        });
    };

    $scope.trust = function() {
        var url = urls.urlProfileTrust + '/user_id/' + $('#userId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.hasTrusted = 2;
                $scope.getTrustInfo($('#userId').val());
            } else {

            }
        });
    };

    $scope.delTrust = function() {
        var url = urls.urlProfileDelTrust + '/user_id/' + $('#userId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.hasTrusted = 1;
                $scope.getTrustInfo($('#userId').val());
            } else {

            }
        });
    };

    $scope.getTaskInfo = function() {
        var url = urls.urlTask + '/mission_id/' + $('#missionId').val();
        $http.get(url).success(function(data) {
            // alert(data.url);
            if (data.status == 1) {
                $scope.mission = data.url;
                $scope.mission.durationMeaning = transDuration($scope.mission.duration);
                $scope.mission.salary = transSalary($scope.mission.salary1, $scope.mission.salary2);
                $scope.mission.location = transLocation($scope.mission.location1, $scope.mission.location2);
                // alert($scope.mission.mission_name)
                $scope.publisher_name = data.url.publisher_name;
                if ($scope.mission.collect_status == 2) {
                    $scope.hasFavored = 2;
                } else {
                    $scope.hasFavored = 1;
                }
                if (data.url.publisher.length != 0) {
                    $scope.publisher = data.url.publisher;
                } else {
                    $scope.publisher = '';
                }
                $scope.publisher_id = data.url.publisher_id;
                $scope.getTrustInfo($scope.publisher_id);
                $scope.getPhone = function() {
                    var url = urls.urlTaskContact + '/publisher_id/' + $scope.publisher_id;
                    $http.get(url).success(function(data) {
                        if (data.status == 1) {
                            $scope.phone = data.url.phone;
                        } else {
                            $scope.phone = '';
                        }
                    });
                };
                $scope.getPhone();
            } else {
                $scope.mission = '';
            }
        });
    };

    $scope.fetchMission = function() {
        var url = urls.urlTaskRecv,
            data = {
                mission_id: $('#missionId').val(),
                message: $('#fetchContent').val()
            },
            transFn = function(data) {
                return $.param(data);
            },
            postCfg = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                transformRequest: transFn
            };
        $http.post(url, data, postCfg)
            .success(function(data) {
                if (data.status == 1) {
                    // window.location.reload();
                    $scope.getTaskInfo();
                    $('#msgModal').modal('hide');
                }
            });
    };

    $scope.favMission = function() {
        var url = urls.urlFavMission + '/mission_id/' + $('#missionId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.getTaskInfo();
            } else {

            }
        });
    };

    $scope.delFavMission = function() {
        var url = urls.urlFavDelMission + '/mission_id/' + $('#missionId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.getTaskInfo();
            } else {

            }
        });
    };

    $scope.showModal = function() {
        $('#msgModal').modal('show');
        $('#msgModal .modal-header').find('h4').text($scope.mission.mission_name);
    };


    $scope.getReportModal = function() {
        $('#reportModal').modal('show');
    };

    $scope.report = function() {
        var url = urls.urlProfileReport,
            data = {
                user_id: $('#userId').val(),
                content: $('#reportContent').val()
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    alert('success');
                } else {
                    //                    alert(data.info);
                }
                $('#reportModal').modal('hide');
                $scope.reportCont = '';
            });
    };

    $scope.getTimePast = getTimePastFunc;
    $scope.getTaskInfo();
}

function manageController($scope, $http) {
    $scope.missionUndone = '';
    $scope.missionDone = '';
    $scope.hash = location.hash.split('#')[1];

    $scope.tablist = function(hashname) {
        $scope.hash = hashname;
    };

    $scope.getMission = function() {
        $http.get(urls.urlManageGetInfo).success(function(data) {
            if (data.status == 1) {
                if (data.url[1] != null) {
                    $scope.missionDone = data.url[1];
                    for (var i = 0; i < $scope.missionDone.length; i++) {
                        $scope.missionDone[i].durationMeaning = transDuration($scope.missionDone[i].duration);
                        $scope.missionDone[i].salary = transSalary($scope.missionDone[i].salary1, $scope.missionDone[i].salary2);
                        $scope.missionDone[i].location = transLocation($scope.missionDone[i].location1, $scope.missionDone[i].location2);
                    }
                }

                if (data.url[0] != null) {
                    $scope.missionUndone = data.url[0];
                    for (var i = 0; i < $scope.missionUndone.length; i++) {
                        $scope.missionUndone[i].durationMeaning = transDuration($scope.missionUndone[i].duration);
                        $scope.missionUndone[i].salary = transSalary($scope.missionUndone[i].salary1, $scope.missionUndone[i].salary2);
                        $scope.missionUndone[i].location = transLocation($scope.missionUndone[i].location1, $scope.missionUndone[i].location2);
                    }
                }

            } else {
                $scope.missionDone = '';
                $scope.missionUndone = '';
            }
        });
    };

    $scope.getTimePast = getTimePastFunc;

    $scope.getMission();
}

function publisherController($scope, $http) {
    $scope.hotSearch = ["导演", "华谊兄弟"];
    $scope.quickSearch = function(oneSearch) {
        $scope.keyword = oneSearch;
        $scope.search();
    };
    $scope.jobs = '';
    $scope.keyword = '';
    $scope.newKeyword = '';
    $scope.loginStatus = false;
    $scope.advert = '';
    $scope.getAdvert = function() {
        var url = urls.urlNewslist;
        $http.get(url).success(function(data) {
            $scope.advert = data;
        });
    }
    var defaultString = '无相关信息'
    getJobs($scope, $http);

    $scope.getAdvert = function() {
        var url = urls.urlNewslist;
        $http.get(url).success(function(data) {
            $scope.advert = data;
        });
    }
    $scope.getAdvert();
    $scope.durations = application.getDurations();

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
        $scope.search();
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
        $scope.search();
    };
    $scope.transExperience = function(experience) {
        if (experience) {
            return experience.project_name + ' ' + experience.role;
        } else {
            return '--';
        }
    }

    $scope.userinfo = '';
    var page = 1,
        row = 10;

    //$("#keyword-input").bind('keyup',function(event){
    //    if(event.keyCode == 13){
    //        $scope.search();
    //    }
    //});

    if ($('#user-name').val()) {
        $scope.loginStatus = true;
    }
    $scope.username = function(name) {
        if ($scope.loginStatus) {
            return name;
        } else {
            return '--';
        }
    }

    $scope.search = function() {
        var jobs = getActiveTag($scope.jobs, 'stat_name'),
            durations = getActiveTag($scope.durations, 'id');
        $scope.url = urls.urlYFInfo + "?page=1" + "&row=" + row + '&jobs=' + jobs + '&duration=' + durations + '&keyword=' + $scope.keyword;
        $http.get($scope.url).success(function(data) {
            if (data.status == 1) {
                $scope.userinfo = data.url;
                $scope.newKeyword = $scope.keyword;
                page = 2;
            } else {
                alert("没有满足搜索条件记录");
                $scope.userinfo = "";
            }
        });
    }

    $scope.getYFInfo = function() {
        $http.get(urls.urlYFInfo + "?page=" + page + "&row=" + row).success(function(data) {
            if (data.status == 1) {
                $scope.userinfo = data.url;
                $scope.userinfo.forEach(function(user) {
                    user.degreeMeaning = genDegreeInfo(user);
                });
                page++;
            };
        });
    };


    $scope.fetchYFInfo = function() {
        var jobs = getActiveTag($scope.jobs, 'stat_name'),
            durations = getActiveTag($scope.durations, 'id');
        $scope.url = urls.urlYFInfo + "?page=" + page + "&row=" + row + '&jobs=' + jobs + '&duration=' + durations + '&keyword=' + $scope.newKeyword;
        $http.get($scope.url).success(function(data) {
            if (data.status == 1) {
                $scope.userinfo = $scope.userinfo.concat(data.url);
                page++;
            } else {
                alert("没有更多信息");
            }
        });
    };

    $scope.publish = function() {
        window.location.href = urls.urlPublishPub;
    };
    $scope.getYFInfo();
    $scope.getAdvert();
}

function manageFetcherController($scope, $http) {
    $scope.missionUndone = '';
    $scope.missionDone = '';
    $scope.missionPicked = '';
    $scope.hash = location.hash.split('#')[1];

    $scope.tablist = function(hashname) {
        $scope.hash = hashname;
    };

    $scope.getMission = function() {
        $http.get(urls.urlManageFetcher).success(function(data) {
            if (data.status == 1) {
                // if (data.url[1] != null) {
                //     $scope.missionDone = data.url[1];
                //     for (var i = 0; i < $scope.missionDone.length; i++) {
                //         $scope.missionDone[i].durationMeaning = transDuration($scope.missionDone[i].duration);
                //         $scope.missionDone[i].salary = transSalary($scope.missionDone[i].salary1, $scope.missionDone[i].salary2);
                //         $scope.missionDone[i].location = transLocation($scope.missionDone[i].location1, $scope.missionDone[i].location2);
                //     }
                // }

                // if (data.url[0] != null) {
                //     $scope.missionUndone = data.url[0];
                //     for (var i = 0; i < $scope.missionUndone.length; i++) {
                //         $scope.missionUndone[i].durationMeaning = transDuration($scope.missionUndone[i].duration);
                //         $scope.missionUndone[i].salary = transSalary($scope.missionUndone[i].salary1, $scope.missionUndone[i].salary2);
                //         $scope.missionUndone[i].location = transLocation($scope.missionUndone[i].location1, $scope.missionUndone[i].location2);
                //     }
                // }
                if (!isEmpty(data.url[0])) {
                    $scope.missionUndone = data.url[0];
                    for (var i = 0; i < $scope.missionUndone.length; i++) {
                        $scope.missionUndone[i].durationMeaning = transDuration($scope.missionUndone[i].duration);
                        $scope.missionUndone[i].salaryMeaning = transSalary($scope.missionUndone[i].salary1, $scope.missionUndone[i].salary2);
                        $scope.missionUndone[i].locationMeaning = transLocation($scope.missionUndone[i].location1, $scope.missionUndone[i].location2);
                    }
                }

                if (!isEmpty(data.url[1])) {
                    $scope.missionPicked = data.url[1];
                    for (var i = 0; i < $scope.missionPicked.length; i++) {
                        $scope.missionPicked[i].durationMeaning = transDuration($scope.missionPicked[i].duration);
                        $scope.missionPicked[i].salaryMeaning = transSalary($scope.missionPicked[i].salary1, $scope.missionPicked[i].salary2);
                        $scope.missionPicked[i].locationMeaning = transLocation($scope.missionPicked[i].location1, $scope.missionPicked[i].location2);
                    }
                }

                if (!isEmpty(data.url[2])) {
                    $scope.missionDone = data.url[2];
                    for (var i = 0; i < $scope.missionDone.length; i++) {
                        $scope.missionDone[i].durationMeaning = transDuration($scope.missionDone[i].duration);
                        $scope.missionDone[i].salaryMeaning = transSalary($scope.missionDone[i].salary1, $scope.missionDone[i].salary2);
                        $scope.missionDone[i].locationMeaning = transLocation($scope.missionDone[i].location1, $scope.missionDone[i].location2);
                    }
                }

            } else {
                $scope.missionDone = '';
                $scope.missionUndone = '';
            }
        });
    };

    $scope.getTimePast = getTimePastFunc;
    $scope.getMission();
}

function missionModifyController($scope, $http, $q) {
    $scope.mission = '';
    $scope.isPhonePublic = false;
    $scope.isAgentPublic = false;

    $scope.jobs = '';
    $scope.salary2 = '';
    $scope.location2 = '';
    $scope.salary = application.getSalary();
    $scope.locations = application.getLocations();
    $scope.province = '';
    $scope.city = '';
    $scope.provinces = application.getProvinces();
    $scope.cities = new Array();
    $scope.validTimes = application.getValidTime();
    $scope.durations = application.getDurations();
    $scope.durationMeaning = getActiveTag($scope.durations, 'id');
    $http.get(urls.urlGetJobs).success(function(data) {
        if (data.status == 1) {
            $scope.jobs = data.url;
            for (var i = 0; i < $scope.jobs.length; i++) {
                $scope.jobs[i].active = false;
            }
            $scope.getTaskInfo();
        } else {
            $scope.jobs = '';
        }
    });

    $('#selectP').on('change', function() {
        var province = $(this).find("option:selected").text();
        $scope.city = '';
        $scope.cities = application.getCities()[province];
    });

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
        $scope.jobMeaning = getActiveTag($scope.jobs, 'stat_name');
        console.log($scope.jobMeaning);
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
        $scope.durationMeaning = getActiveTag($scope.durations, 'id');
    };

    $scope.getTaskInfo = function() {
        var url = urls.urlManageDetail + '/mission_id/' + $('#missionId').val();
        $http.get(url).success(function(data) {
            // alert(data.url);
            if (data.status == 1) {
                $scope.mission = data.url;
                $scope.isPhonePublic = ($scope.mission.isphone_public == 2);
                $scope.isAgentPublic = ($scope.mission.agent == 2);
                $scope.durationMeaning = transDuration($scope.mission.duration);
                if ($scope.mission.location2 != '') {
                    $scope.province = $scope.mission.location2.split(',')[0];
                    $scope.cities = application.getCities()[$scope.province];
                    $scope.city = $scope.mission.location2.split(',')[1];
                }
                setActiveTag($scope.mission.jobs, $scope.jobs, 'stat_name');
                $scope.jobMeaning = getActiveTag($scope.jobs, 'stat_name');
                setActiveTag($scope.mission.duration, $scope.durations, 'id');
            } else {
                $scope.mission = '';
                $scope.status = 2;
            }
        });
    };

    $scope.submit = function() {
        if ($scope.mission.location1 == 3) {
            $scope.mission.location2 = $scope.province + ',' + $scope.city;
        } else {
            $scope.mission.location2 = '';
        }

        if ($scope.mission.salary1 != 1) {
            $scope.mission.salary2 = '';
        }


        var jobs = $scope.jobMeaning,
            durations = $scope.durationMeaning,
            url = urls.urlManageSubmit,
            data = {
                mission_id: $scope.mission.mission_id,
                mission_name: $scope.mission.mission_name,
                jobs: jobs,
                duration: durations,
                salary1: $scope.mission.salary1,
                salary2: $scope.mission.salary2,
                location1: $scope.mission.location1,
                location2: $scope.mission.location2,
                description: $scope.mission.description,
                valid_time: $scope.mission.valid_time,
                isagent: ($scope.isAgentPublic * 1) + 1,
                isphone_public: ($scope.isPhonePublic * 1) + 1
            };
        if (isEmpty(jobs)) {
            alert("请至少选择一个岗位");
            return;
        }
        if (isEmpty(durations)) {
            alert("请至少选择一个工作时限");
            return;
        }

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    alert("发布成功！");
                    window.location.href = urls.urlTaskDetail + "?mission=" + $scope.mission.mission_id;
                } else {
                    alert(data.info);
                }
            });
    };
}

function missionIndexController($scope, $http) {
    $scope.mission = '';
    $scope.userFollow = '';
    $scope.userReceived = '';
    $scope.follower = '';
    $scope.receiver = '';
    $scope.status = '';
    $scope.rank = 0;
    $('.rank').rater({
        active: true,
        style: 'inline-normal',
        maxvalue: 5
    });


    $scope.getTaskInfo = function() {
        var url = urls.urlTask + '/mission_id/' + $('#missionId').val();
        $http.get(url).success(function(data) {
            // alert(data.url);
            if (data.status == 1) {
                $scope.mission = data.url;
                $scope.mission.durationMeaning = transDuration($scope.mission.duration);
                $scope.mission.salary = transSalary($scope.mission.salary1, $scope.mission.salary2);
                $scope.mission.location = transLocation($scope.mission.location1, $scope.mission.location2);
            } else {
                $scope.mission = '';
            }
        });
    };

    $scope.getMissionDetail = function() {
        var url = urls.urlManageDetail + '/mission_id/' + $('#missionId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.userFollow = data.url.follow;
                $scope.userReceived = data.url.receive;
                console.log($scope.userReceived);
                $scope.status = data.url.status;
                console.log($scope.userReceived);
            }
        });
    };
    $scope.getFollowerModal = function(index) {
        if ($scope.status == 2) {
            window.location.href = urls.urlProfileIndex + '?user_id=' + $scope.userFollow[index].follower_id;
            return;
        }
        if (!isEmpty($scope.userFollow)) {
            $scope.follower = $scope.userFollow[index];
            $scope.follower.hasFavored = $scope.follower.collect_status;
        }
        $('#followerModal').modal('show');
    };
    $scope.getReceiverModal = function(index) {
        if ($scope.status == 2) {
            window.location.href = urls.urlProfileIndex + '?user_id=' + $scope.userReceived[index].follower_id;
            return;
        }
        if (!isEmpty($scope.userReceived)) {
            $scope.receiver = $scope.userReceived[index];
            $scope.receiver.hasFavored = $scope.receiver.collect_status;
            $scope.receiver.hasEvaluated = (!isEmpty($scope.receiver.evaluate) * 1);
        }
        $('#receiverModal').modal('show');
    };

    $scope.select = function() {
        var url = urls.urlProfileSelect,
            data = {
                mission_id: $('#missionId').val(),
                follower_id: $scope.follower.user_id
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    window.location.reload();
                } else {
                    //                    alert(data.info);
                }
                $('#followerModal').modal('hide');
                $scope.follower = '';
                $scope.getMissionDetail();
            });
    };

    $scope.refuse = function() {
        var url = urls.urlManageRefuse,
            data = {
                mission_id: $('#missionId').val(),
                user_id: $scope.receiver.user_id
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    window.location.reload();
                } else {
                    //                    alert(data.info);
                }
                $('#receiverModal').modal('hide');
                $scope.receiver = '';
                $scope.getMissionDetail();
            });
    };

    $scope.finish = function(opt) {
        if ($scope.userReceived) {
            for (var i = 0; i < $scope.userReceived.length; i++) {
                $scope.userReceived[i].is_selected = true;
            }
        }

        var url = urls.urlManageFinish,
            data = {
                mission_id: $('#missionId').val(),
                actor_info: $scope.userReceived,
                evaluate: opt
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    window.location.href = urls.urlManagePublisher;
                } else {
                    alert(data.info);
                }
            });
    };

    $scope.getTimePast = getTimePastFunc;


    $scope.getTaskInfo();
    $scope.getMissionDetail();

    $scope.favUser = function(id) {
        if (id == 1) {
            favUser($scope.receiver.user_id, $http);
            $scope.receiver.hasFavored = 2;
        } else {
            favUser($scope.follower.user_id, $http);
            $scope.follower.hasFavored = 2;
        }
        $scope.getMissionDetail();
    };

    $scope.delFavUser = function(id) {
        if (id == 1) {
            delFavUser($scope.receiver.user_id, $http);
            $scope.receiver.hasFavored = 1;
        } else {
            delFavUser($scope.follower.user_id, $http);
            $scope.follower.hasFavored = 1;
        }
        $scope.getMissionDetail();
    };

    $scope.select = function() {
        var url = urls.urlProfileSelect,
            data = {
                mission_id: $('#missionId').val(),
                follower_id: $scope.follower.user_id
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
                $('#followerModal').modal('hide');
                $scope.follower = '';
                $scope.getMissionDetail();
            });
    };

    /*$scope.evaluate = function(receiver) {
        if (receiver.hasEvaluated) {
            $scope.rank = 0;
            $('#receiverModal').modal('hide');
            return;
        }
        var url = urls.urlManageEvaluate,
            data = {
                evaluate: $scope.rank,
                mission_id: $('#missionId').val(),
                user_id: $scope.receiver.user_id
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
                $('#receiverModal').modal('hide');
                $scope.receiver = '';
                $scope.getMissionDetail();
            });
    };*/

    $scope.refuse = function() {
        console.log($scope.mission);
        var url = urls.urlManageRefuse,
            data = {
                mission_id: $('#missionId').val(),
                user_id: $scope.receiver.user_id
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
                $('#receiverModal').modal('hide');
                $scope.receiver = '';
                $scope.getMissionDetail();
            });
    };
}

function postCfg(data) {
    return {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        transformRequest: function(data) {
            return $.param(data);
        }
    };
}

function getTimePastFunc(datetime) {
    if (!datetime) {
        return;
    }
    var curTime = new Date(),
        pastTime = new Date(datetime.replace(' ', 'T') + '+08:00'),
        duration = 0,
        result = '';
    duration = (curTime.getTime() - pastTime.getTime()) / 1000;
    if (duration > 0 && duration < 60) {
        result = '刚刚';
    } else if (duration >= 60 && duration < 60 * 60) {
        result = Math.ceil(duration / 60) + '分钟前';
    } else if (duration >= 60 * 60 && duration < 60 * 60 * 24) {
        result = Math.ceil(duration / (60 * 60)) + '小时前'
    } else if (duration >= 60 * 60 * 24) {
        result = Math.ceil(duration / (60 * 60 * 24)) + '天前'
    }
    return result;
}


// Favorite user
function favUser(userId, $http, callback) {
    var url = urls.urlFavUser + '/user_id/' + userId;
    $http.get(url).success(function(data) {
        if (data.status == 1) {
            //            alert("收藏成功");
            callback();
        } else {
            alert('收藏失败');
        }
    });
}

function delFavUser(userId, $http, callback) {
    var url = urls.urlFavDelUser + '/user_id/' + userId;
    $http.get(url).success(function(data) {
        if (data.status == 1) {
            //                alert("删除成功");
            callback();
        } else {
            alert('取消收藏失败');
        }
    });
}

function cloakController($scope, $http) {
    $scope.userState = '';

    $scope.cloak = function() {
        $http.get(urls.urlSelfCloak).success(function(data) {
            if (data.status == 1) {
                $scope.getUserState();
            }
        });
    };

    $scope.unCloak = function() {
        $http.get(urls.urlSelfUnCloak).success(function(data) {
            if (data.status == 1) {
                $scope.getUserState();
            }
        });
    };

    $scope.getUserState = function() {
        $http.get(urls.urlGetUserState).success(function(data) {
            if (data.status == 1) {
                $scope.userState = data.url;
            } else {
                $scope.userState = '';
            }
        });
    };
    $scope.getUserState();
}

function resetPasswdController($scope, $http) {
    $scope.timer = 60;
    $scope.timeInterval;
    $scope.timerIsShow = false;

    var codeTimer = function() {
        var updateTimer = function() {
            $scope.timer--;
            if ($scope.timer <= 0) {
                $scope.timerIsShow = false;
                clearInterval($scope.timeInterval);
            }
        };
        $scope.timeInterval = setInterval(function() {
            $scope.$apply(updateTimer);
        }, 1000);

        $scope.timerIsShow = true;
        updateTimer();
    };

    $scope.getVerifyCode = function() {
        var url = urls.urlLoginGetVerifyCode + '/phone/' + $scope.phone;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                alert("验证码已发送");
                codeTimer();
            } else {
                alert(data.info);
            }
        });
    };

    $scope.submit = function() {
        var url = urls.urlResetPsw,
            data = {
                passwd: hex_md5($scope.password),
                verfiCode: $scope.verifyCode,
                confirm_passwd: hex_md5($scope.passwordRepeat),
                phone: $scope.phone
            },
            transFn = function(data) {
                return $.param(data);
            },
            postCfg = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                transformRequest: transFn
            };
        if ($scope.phone == '') {
            alert("请填写手机号");
            return;
        }
        if ($scope.verifyCode == '') {
            alert("请输入验证码");
            return;
        }
        if ($scope.password == '') {
            alert("请填写密码");
            return;
        }
        if ($scope.password != $scope.passwordRepeat) {
            alert('两次密码输入不一致');
            return;
        };
        if ($scope.error) {
            alert(errInfo);
            return;
        }

        $http.post(url, data, postCfg)
            .success(function(data) {
                if (data.status == 1) {
                    window.location.href = urls.urlResumeModify;
                } else {
                    alert(data.info);
                }
            });
    };
}